package dao.implDao;


import model.Gift;
import org.hibernate.Session;
import util.HibernateUtil;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IDEA.
 * User: Ѱ
 * Date: 20.07.14
 * Time: 12:09
 **/
public class GiftsDao {


    public void add(Gift gift) throws SQLException {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.save(gift);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public List<Gift> getAll() throws SQLException{
        Session session = null;
        List<Gift> giftsList = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            giftsList = session.createCriteria(Gift.class).list();
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return giftsList;
    }

    public Gift getGiftById(Long id) throws SQLException{
        Iterator<Gift> iter = getAll().iterator();
        Gift tmp;
        while (iter.hasNext()) {
            tmp = iter.next();
            if (tmp.getId() == id) {
                return tmp;
            }
        }
        return null;
    }

    public void update(Gift gift) throws SQLException{

        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.update(gift);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void delete(Gift gift) throws SQLException{
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.delete(gift);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
